<?php
namespace backend\logic;

use think\Db;
use external\SFTools;
use think\db\Where;
use think\facade\Log;

class GoodsLogic {
    
    /**
     * 获取床套SN码列表
     * @param page
     * @param size
     * @param search_value
     * */
    public function getSnListCt($keyword, $fStartDate, $fEndDate, $bc, $page, $size){
        
        if (empty($fStartDate)) {
            return SFTools::err("3300", array("fStartDate" => $fStartDate));
        }
        if (empty($fEndDate)) {
            return SFTools::err("3300", array("fEndDate" => $fEndDate));
        }
        $where = new Where();
        $snList = array();
        if (!empty($keyword)) {
            $result = $this->addSnCodeCt($keyword);
            if (!empty($result['error_code'])) {
                return $result;
            }
            if (!empty($result)) {
                $snList[] = $result;
                return $snList;
            }
        }
    
        $snList = Db::table('v_sn_list_ct')->field('*')->where($where)->whereTime('create_datetime', 'between', [$fStartDate, $fEndDate])->page($page, $size)->order('create_datetime', 'DESC')->select();
        if($snList){
            $fMONo_arr = [];
            foreach ($snList as $k => $v){
                if(!isset($fMONo_arr[$v['fMONo']])){
                    $fMONo_arr[$v['fMONo']]['done'] = Db::table('v_sn_list_ct')->where(['fMONo'=>$v['fMONo']])->count();
                    $fMONo_arr[$v['fMONo']]['all'] = Db::table('[SuiB_ERP].[dbo].[t_MPSM_MOItem]')->where(['fMONo'=>$v['fMONo']])->group('fMONo')->sum('fMoQty');
                }
                $snList[$k]['done'] = $fMONo_arr[$v['fMONo']]['done'];
                $snList[$k]['all'] = $fMONo_arr[$v['fMONo']]['all'];
            }
        }
        
        return $snList;
    }
    
    /**
     * 获取床网SN码列表
     * @param page
     * @param size
     * @param search_value
     * */
    public function getSnListCw($keyword, $fStartDate, $fEndDate, $bc, $fSupplierCode, $page, $size, $view){
        
        if (empty($fStartDate)) {
            return SFTools::err("3300", array("fStartDate" => $fStartDate));
        }
        if (empty($fEndDate)) {
            return SFTools::err("3300", array("fEndDate" => $fEndDate));
        }
        $where = new Where();
        $snList = array();
        if (empty($keyword)) {
            if (!empty($bc)) {
                if ($bc == '1') {
                    $where['fMONo'] = ['not null'];
                }
                if ($bc == '2') {
                    $where['fMONo'] = ['null'];
                }
            }
            if (!empty($fSupplierCode)) {
                $where['fSupplierCode'] = $fSupplierCode;
            }
        }else{
            $result = $this->addSnCodeCw($keyword);
            if (!empty($result['error_code'])) {
                return $result;
            }
            if (!empty($result)) {
                if ($view == '2') {
                    $snList[] = $result;
                    return $snList;
                } else {
                    return SFTools::err("3603");
                }
            }
        }
    
        if ($view == '2') {
            $field = 'barcode_cw_uuid,barcode,fSupplierCode,fModelCodeCW,fModelNameCW,fModelDescCW,sync_datetime,fUse,fMONo,create_datetime';
            $snList = Db::table('v_sn_list_cw')->field($field)->where($where)->whereTime('sync_datetime', 'between', [$fStartDate, $fEndDate])->page($page, $size)->order('sync_datetime', 'DESC')->select();
        } else {
            $field = 'fModelCodeCW,fModelNameCW,fModelDescCW,fSupplierCode,COUNT(barcode_cw_uuid) fTotal,SUM(fUse) fUse';
            $snList = Db::table('v_sn_list_cw')->field($field)->where($where)->whereTime('sync_datetime', 'between', [$fStartDate, $fEndDate])->group('fModelCodeCW,fModelNameCW,fModelDescCW,fSupplierCode')->select();
        }
        return $snList;
    }
    
    /**
     * 获取床套SN码总数
     * @param page
     * @param size
     * @param search_value
     * */
    public function getSnListCtCount($keyword, $fStartDate, $fEndDate, $bc){
        if (empty($fStartDate)) {
            return SFTools::err("3300", array("fStartDate" => $fStartDate));
        }
        if (empty($fEndDate)) {
            return SFTools::err("3300", array("fEndDate" => $fEndDate));
        }
        $where = new Where();
        if (!empty($bc)) {
            if ($bc == '1') {
                $where['fMONo'] = ['not null'];
            }
            if ($bc == '2') {
                $where['fMONo'] = ['null'];
            }
        }
        $snListCount = Db::table('v_sn_list_ct')->field('*')->where($where)->whereTime('create_datetime', 'between', [$fStartDate, $fEndDate])->count();
        
        return $snListCount;
    }
    
    /**
     * 获取床网SN码总数
     * @param page
     * @param size
     * @param search_value
     * */
    public function getSnListCwCount($keyword, $fStartDate, $fEndDate, $bc, $fSupplierCode){
        if (empty($fStartDate)) {
            return SFTools::err("3300", array("fStartDate" => $fStartDate));
        }
        if (empty($fEndDate)) {
            return SFTools::err("3300", array("fEndDate" => $fEndDate));
        }
        $where = new Where();
        if (!empty($bc)) {
            if ($bc == '1') {
                $where['fMONo'] = ['not null'];
            }
            if ($bc == '2') {
                $where['fMONo'] = ['null'];
            }
        }
        if (!empty($fSupplierCode)) {
            $where['fSupplierCode'] = $fSupplierCode;
        }
        $snListCount = Db::table('v_sn_list_cw')->field('*')->where($where)->whereTime('sync_datetime', 'between', [$fStartDate, $fEndDate])->count();
        
        return $snListCount;
    }
    
    /**
     * 获取床网SN码总数
     * @param page
     * @param size
     * @param search_value
     * */
    public function getSupplierListCw(){
        
        $supplierList = Db::table('v_sn_list_cw')->field('fSupplierCode')->group('fSupplierCode')->select();
        
        return $supplierList;
    }
    
    /**
     * 添加床套SN码
     * @param string $barcode
     * */
    public function addSnCodeCt($barcode){
        $str_length = strlen($barcode);
        if ($str_length <= CT_SN_SUFFIX) {
            return SFTools::err("3309", array("CT_SN_SUFFIX" => $str_length));
        }
        $productionStepCt = new \backend\model\ProductionStepCt;
        $productionStepCtFind = $productionStepCt::where('barcode', $barcode)->find();
        if (empty($productionStepCtFind)) {
            $barcodeFind = Db::table('v_BarcodeFg')->field('*')->where('fBarcode', $barcode)->Find();
            if (empty($barcodeFind)) {
                return SFTools::err("3307");
            }
            $fGoodsID = $barcodeFind['fGoodsID'];
            $fGoodsCode = $barcodeFind['fGoodsCode'];
            $productionBomFind = $this->getBomFind($fGoodsID, $fGoodsCode);
            if (empty($productionBomFind)) {
                return SFTools::err("3602");
            }
            $productionStepCt->fMONo = $barcodeFind['fMONo'];
            $productionStepCt->fGoodsID = $fGoodsID;
            $productionStepCt->barcode = $barcode;
            $productionStepCt->fModelCodeCT = $productionBomFind['fModelCodeCT'];
            $productionStepCt->fModelNameCT = $productionBomFind['fModelNameCT'];
            $productionStepCt->fModelCodeCW = $productionBomFind['fModelCodeCW'];
            $productionStepCt->fModelNameCW = $productionBomFind['fModelNameCW'];
            $productionStepCt->fModelDescCW = $productionBomFind['fModelDescCW'];
            $productionStepCt->save();
            return NULL;
        }
        return $productionStepCtFind;
    }
    
    /**
     * 添加床网SN码
     * @param string $barcode
     * */
    public function addSnCodeCw($barcode){
        $str_length = strlen($barcode);
        if ($str_length <= CW_SN_PREFIX) {
            return SFTools::err("3309", array("CW_SN_PREFIX" => $str_length));
        }
        $barcodeCw = new \backend\model\BarcodeCw;
        $snInfo = $barcodeCw::where('barcode', $barcode)->find();
        if (empty($snInfo)) {
            $cw_code = substr($barcode, 0, CW_SN_PREFIX);
            $fSupplierCode = substr($barcode, CW_SN_PREFIX, 1);
            $barcodeCw->barcode = $barcode;
            $barcodeCw->fSupplierCode = strtoupper($fSupplierCode);
            $barcodeCw->fModelCodeCW = $cw_code;
            $cwFind = $this->getBomCwFind($cw_code);
            if (empty($cwFind)) {
                return SFTools::err("3602");
            }
            $cw_name = $cwFind['fModelNameCW'];
            $cw_desc = $cwFind['fModelDescCW'];
            $barcodeCw->fModelNameCW = $cw_name;
            $barcodeCw->fModelDescCW = $cw_desc;
            $barcodeCw->save();
            return NULL;
        }
        return $snInfo;
    }
    
    /**
     * 根据唯一标识删除床套
     * @param string $barcode_ct_uuid
     * */
    public function delSnInfoCtBuyUUID($barcode_ct_uuid){
        
        if (empty($barcode_ct_uuid)) {
            return SFTools::err("3300", array("barcode_ct_uuid" => $barcode_ct_uuid));
        }
        $productionStepCt = new \backend\model\ProductionStepCt;
        $productionStepCtFind = $productionStepCt::where('barcode_ct_uuid', $barcode_ct_uuid)->find();
        if (!empty($productionStepCtFind)) {
            $productionStepCtFind->delete();
        }
        
        return true;
    }
    
    /**
     * 根据唯一标识删除床网
     * @param string $barcode_cw_uuid
     * */
    public function delSnInfoCwBuyUUID($barcode_cw_uuid){
        
        if (empty($barcode_cw_uuid)) {
            return SFTools::err("3300", array("barcode_cw_uuid" => $barcode_cw_uuid));
        }
        $productionStepCw = new \backend\model\ProductionStepCw;
        $productionStepCwFind = $productionStepCw::where('barcode_cw_uuid', $barcode_cw_uuid)->find();
        if (!empty($productionStepCwFind)) {
            $productionStepCwFind->delete();
        }
        $barcodeCw = new \backend\model\BarcodeCw;
        $barcodeCwFind = $barcodeCw::where('barcode_cw_uuid', $barcode_cw_uuid)->find();
        if (empty($barcodeCwFind)) {
            return SFTools::err("3308", array("barcodeCtFind" => $barcodeCwFind));
        }
        $barcodeCwFind->delete();
        
        return true;
    }
    
    /**
     * 导入Excel
     * @return NULL
     */
    public function importExcel($userFind) {
        error_reporting(E_ALL);
        ini_set('display_errors', true);
        ini_set('display_startup_errors', true);
        date_default_timezone_set('Asia/Shanghai');
        ini_set("memory_limit", "1024M");
        set_time_limit(0);
        
        if (empty($userFind['user_uuid'])) {
            return SFTools::err("3300", array("user_uuid" => $userFind['user_uuid']));
        }
//         if (empty($userFind['login_account'])) {
//             return SFTools::err("3300", array("login_account" => $userFind['login_account']));
//         }
        
        $filePath = $_FILES['excel']['tmp_name'];
        $fStartRow = 2;
        
//         $excel = new \external\Excel();
//         $return_arr = $excel->importExcel($filePath, $fStartRow);
        $return_arr = $this->importExcelCommon($filePath, $fStartRow);
        unlink($filePath);
        
        $barcodeCw = new \backend\model\BarcodeCw;
        $barcodeCw::where('create_datetime', 'LT', date('Y-m-d H:i:s', strtotime('-2 days', time())))->delete();
        
        if($return_arr){
//             $BarcodeCw = new \backend\model\BarcodeCw();
//             $dataSet = [];
            
            foreach ($return_arr as $k => $v) {
                $this->addSnCodeCw($v[0]);
                
//                 if(!$v[2]) continue;
                
//                 $dataSet[] = [
//                     'barcode' => $v[0],
//                     'fSupplierCode' => $v[1],
//                     'fModelCodeCW' => $v[2],
//                     'fModelNameCW' => $v[3],
//                     'fModelDescCW' => $v[3],
//                 ];
                
//                 if($dataSet && count($dataSet)>=1000){
//                     $BarcodeCw->saveAll($dataSet);
//                     $dataSet = [];
//                 }
            }
            
//             if($dataSet){
//                 $BarcodeCw->saveAll($dataSet);
//                 $dataSet = [];
//             }
        }
        
        return true;
    }
    
    /**
     * 导入excel
     * @param string $filePath  文件路径 + 文件名
     * @param int    $fStartRow 开始行（默认第二行）
     */
    public function importExcelCommon($filePath, $fStartRow = 2){
        require \think\facade\Env::get('root_path') . 'extend/' . 'external/PHPExcel/PHPExcel/IOFactory.php';
        require \think\facade\Env::get('root_path') . 'extend/' . 'external/PHPExcel/PHPExcel.php';
        
        $PHPReader = new \PHPExcel_Reader_Excel5();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel2007();
            if (!$PHPReader->canRead($filePath)) {
                return false;
            }
        }
        $fExcel = $PHPReader->load($filePath);
        /**读取excel文件中的第一个工作表*/
        $currSheet = $fExcel->getSheet(0);
        /**取得一共有多少行*/
        $fMaxRow = $currSheet->getHighestRow();
        //        if ($fMaxRow > 1000) {
        //            $fMaxRow = 1000;
        //        }
        /**取得最大的列号*/
        $fMaxColumn = $currSheet->getHighestColumn();
        $fMaxColumn++;
        $returnArr = array();
        /**循环行*/
        for ($r = $fStartRow; $r <= $fMaxRow; $r++) {
            $info = array();
            for ($c = 'A'; $c != $fMaxColumn; $c++) {
                $coordinates = $c . $r;
                $info[] = trim($currSheet->getCell($coordinates)->getFormattedValue());
            }
            $returnArr[] = $info;
        }
        
        return $returnArr;
    }
    
    /**
     * 导出Excel
     * @param
     * @param
     * @param
     * */
    public function exportExcel($keyword, $fStartDate, $fEndDate, $bc, $fSupplierCode, $view){
        
        $snList = $this->getSnListCw($keyword, $fStartDate, $fEndDate, $bc, $fSupplierCode, 1, 30000, $view);
        if (empty($snList)) {
            return false;
        }
        $columns = array('A', 'B', 'C', 'D', 'E', 'F'); //容器
        if ($view == '2') {
            $title = array(array('barcode', '条码'), array('fSupplierCode', '厂家代码'), array('fModelCodeCW', '床网型号'), array('fModelNameCW', '床网名称'), array('fModelDescCW', '床网描述'), array('sync_datetime', '记录时间')); //标题
        } else {
            
            $title = array(array('fSupplierCode', '厂家代码'), array('fModelCodeCW', '床网型号'), array('fModelNameCW', '床网名称'), array('fModelDescCW', '床网描述'), array('fTotal', '床网数量'), array('fUse', '已使用数量')); //标题
        }
        $excel = new \external\Excel();
        $excel->exportExcel($columns, $title, $snList);
    }
    
    /**
     * 记录并返回BOM信息
     */
    public function getBomFind($fGoodsID, $fGoodsCode){
        $productionBom = new \backend\model\ProductionBom;
        $productionBomFind = $productionBom::where('fModelCodeCT', $fGoodsCode)->find();
        if (empty($productionBomFind)) {
            $productionBom->fGoodsID = $fGoodsID;
            $productionBom->fModelCodeCT = $fGoodsCode;
            $productionBomFind['fGoodsID'] = $fGoodsID;
            $productionBomFind['fModelCodeCT'] = $fGoodsCode;
            $productionBomFind['fModelNameCT'] = NULL;
            $productionBomFind['fModelCodeCW'] = NULL;
            $productionBomFind['fModelNameCW'] = NULL;
            $ctFind = Db::connect('oracle_config')->table('F4101')->field('IMDSC1,IMDSC2')->whereRaw("RTRIM(IMLITM) = '" . $fGoodsCode . "'")->Find();
            if (!empty($ctFind)) {
                $ct_name = trim($ctFind['IMDSC1']);
                $productionBom->fModelNameCT = $ct_name;
                $productionBomFind['fModelNameCT'] = $ct_name;
            }
            $snList = Db::connect('oracle_config')->table('F3002')->field('IXKITA,IXAITM')->whereRaw("RTRIM(IXKITA) = '" . $fGoodsCode . "'")->group('IXKITA,IXAITM')->select();
            $productionBomFind['fModelCodeCW'] = NULL;
            $productionBomFind['fModelNameCW'] = NULL;
            $productionBomFind['fModelDescCW'] = NULL;
            if (!empty($snList)) {
                foreach ($snList as $key => $val) {
                    $cw_code = trim($val['IXAITM']);
                    if (!empty($cw_code)) {
                        $prefix = substr($cw_code, 0, 2);
                        if ($prefix == 'YF') {
                            $productionBom->fModelCodeCW = $cw_code;
                            $productionBomFind['fModelCodeCW'] = $cw_code;
                            $cwFind = $this->getBomCwFind($cw_code);
                            if (!empty($cwFind)) {
                                $cw_name = $cwFind['fModelNameCW'];
                                $cw_desc = $cwFind['fModelDescCW'];
                                $productionBom->fModelNameCW = $cw_name;
                                $productionBom->fModelDescCW = $cw_desc;
                                $productionBomFind['fModelNameCW'] = $cw_name;
                                $productionBomFind['fModelDescCW'] = $cw_desc;
                            }
                            break;
                        }
                    }
                }
            }
            $productionBom->save();
        }
        
        return $productionBomFind;
    }
    
    /**
     * 记录并返回床网的BOM信息
     */
    public function getBomCwFind($fModelCodeCW){
        $productionBomCw = new \backend\model\ProductionBomCw;
        $cwFind = $productionBomCw::where('fModelCodeCW', $fModelCodeCW)->find();
        $productionBomCwFind = array();
        $productionBomCwFind['fModelCodeCW'] = $fModelCodeCW;
        if (empty($cwFind)) {
            $cwFind = Db::connect('oracle_config')->table('F4101')->field('IMDSC1,IMDSC2')->whereRaw("RTRIM(IMLITM) = '" . $fModelCodeCW . "'")->Find();
            if (!empty($cwFind)) {
                $cw_name = trim($cwFind['IMDSC1']);
                $cw_desc = trim($cwFind['IMDSC2']);
            }
            $productionBomCw->fModelCodeCW = $fModelCodeCW;
            $productionBomCw->fModelNameCW = $cw_name;
            $productionBomCw->fModelDescCW = $cw_desc;
            $productionBomCw->save();
            $productionBomCwFind['fModelNameCW'] = $cw_name;
            $productionBomCwFind['fModelDescCW'] = $cw_desc;
        } else {
            $productionBomCwFind['fModelNameCW'] = $cwFind['fModelNameCW'];
            $productionBomCwFind['fModelDescCW'] = $cwFind['fModelDescCW'];
        }
        
        return $productionBomCwFind;
    }
    
}